<template>
  <div class="employees">
    <div class="employees__header">
      <span style="color: red;">*</span>
      注：新录入的员工默认密码为 <span style="color: #1890ff;">123456</span>
    </div>
    <div class="employees__enter card">
      <el-form
        ref="elFormRef"
        :model="formData"
        style="width: 50%;"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item
          prop="name"
          label="姓名"
        >
          <el-input
            v-model="formData.name"
            placeholder="请输入姓名"
          />
        </el-form-item>

        <el-form-item
          prop="phone"
          label="电话"
        >
          <el-input
            v-model="formData.phone"
            placeholder="请输入手机号"
          />
        </el-form-item>

        <el-form-item
          prop="gender"
          label="性别"
        >
          <el-radio-group v-model="formData.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          prop="identity_card"
          label="身份证号"
        >
          <el-input
            v-model="formData.identity_card"
            placeholder="请输入身份证号"
          />
        </el-form-item>

        <el-form-item

          prop="birthday_at"
          label="出生年月"
          style="margin-bottom: 0;"
        >
          <el-date-picker
            v-model="formData.birthday_at"
            disabled
            :picker-options="pickerOptions"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>

      </el-form>
    </div>

    <div class="employees__footer card">
      <el-button
        type="danger"
        size="medium"
        @click="reset"
      >
        重置
      </el-button>

      <el-button
        type="primary"
        size="medium"
        :loading="loading"
        @click="submit"
      >
        提交
      </el-button>
    </div>
  </div>
</template>
<script>
import { getFieldsList } from '@/api/customFields.js'
import { batchImport } from '@/api/v2/entry'
import dayjs from 'dayjs'
export default {
  data() {
    return {
      formData: {
        name: '',
        phone: '',
        identity_card: '',
        gender: '男',
        birthday_at: null
      },
      password: '123456',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: ['change', 'blur'] }],
        phone: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请输入手机号'))
              } else if (!/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/.test(value)) {
                callback(new Error('请输入正确的手机号'))
              } else {
                callback()
              }
            },
            message: '请输入正确手机号',
            trigger: ['change', 'blur']
          }
        ],
        identity_card: [
          {
            required: true,
            message: '请输入身份证号',
            trigger: ['blur', 'change']
          },
          {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/g,
            transform(value) {
              return String(value)
            },
            message: '身份证号有误'
          }
        ],
        gender: [{ required: true, message: '请选择性别', trigger: ['change', 'blur'] }],
        birthday_at: [{ required: true, message: '请选择出生年月', trigger: ['change', 'blur'] }]
      },
      fieldMap: {},
      loading: false
    }
  },
  computed: {
    identityCardRegex() {
      const reg = new RegExp(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/g)
      return reg.test(this.formData.identity_card)
    }
  },
  watch: {
    'formData.identity_card': {
      immediate: true,
      handler: function(n) {
        const reg = new RegExp(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/g)
        if (reg.test(n)) {
          const birthday = n.slice(6, 14).replace(/(.{4})(.{2})/, '$1-$2-')
          this.formData.birthday_at = dayjs(birthday).format('YYYY-MM-DD')
        } else {
          this.formData.birthday_at = null
        }
      }
    }
  },
  created() {
    // this.getFieldsList()
  },
  methods: {
    async getFieldsList() {
      try {
        const data = ['user_details', 'user_companys']
        const res = await getFieldsList({ table: JSON.stringify(data) })
        for (const item of res.data) {
          this.fieldMap[item.field] = item
        }
      } catch (error) {
        throw new Error(error?.message)
      }
    },

    submit() {
      this.$refs.elFormRef.validate(valid => {
        if (!valid) return this.$message.error('请将信息填写完整')
        this.entryEmployees({
          data: JSON.stringify([{ ...this.formData, number: 1 }]),
          password: this.password
        })
      })
    },

    async entryEmployees(params) {
      this.loading = true
      try {
        const res = await batchImport(params)
        if (res.data.length > 0) {
          this.$message.error('该手机号已被注册')
        } else {
          this.$message.success('员工录入成功')
          this.reset()
        }
      } catch (error) {
        this.$message.error('员工录入失败')
      } finally {
        this.loading = false
      }
    },

    refresh() {
      this.reset()
    },

    reset() {
      this.$refs.elFormRef.resetFields()
    }

  }
}

</script>
<style lang="scss" scoped>
.employees {
  padding: 20px;

  &__header {
    padding: 10px;
    background-color: #fff;
    border-radius: 5px;
  }

  &__enter {
    margin-top: 20px;
    padding: 20px;
    display: flex;
    justify-content: center;
  }

  &__footer {
    padding: 10px;
    margin-top: 20px;
  }

  .card {
    background-color: #fff;
    border-radius: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
